import 'dart:math' as math;

import 'package:dio/dio.dart';
import 'package:logger/logger.dart';

import 'CheckLogFilter.dart';

class MLogInterceptor extends Interceptor {
  var logger = Logger(filter: CheckLogFilter());

  @override
  Future onRequest(RequestOptions options) {
//    // TODO: implement onRequest
//    logger.e("*** Request ***");
    StringBuffer sb=StringBuffer();
    sb.writeln("*** DioRequst ***:");
    sb.writeln("uri:     ${options.uri}");
    sb.writeln("----------------------------------------------------------------------------------------------------------------");
    sb.writeln(options.headers.toString());
    sb.writeln("----------------------------------------------------------------------------------------------------------------");
    if(options.data is FormData){
      sb.write("{");
      (options.data as FormData).fields.forEach((it){
        sb.write(it.key);
        sb.write(":");
        sb.write(it.value);
        if((options.data as FormData).fields.last!=it){
          sb.write(" , ");
        }
      });
      sb.write("}");
      logger.i(sb.toString());
      sb.clear();
    }else{
      logger.i(options.data.toString());
    }

    return super.onRequest(options);
  }

//  @override
//  Future onError(DioError err) {
//    // TODO: implement onError
//    StringBuffer sb=StringBuffer();
//    sb.writeln("*** DioErrorUri ***:");
//    sb.writeln("uri:       ${err.request.uri}");
//    sb.writeln("----------------------------------------------------------------------------------------------------------------");
//    sb.writeln("*** DioError ***:");
//    sb.write(err.toString());
//    logger.e(sb.toString());
////    if (err.response != null) {
////      sb.clear();
////      sb.write(err.response);
////      logger.e(sb.toString());
////    }
//    return super.onError(err);
//  }

  @override
  Future onResponse(Response response) {
    StringBuffer sb=StringBuffer();
    sb.writeln("*** DioResponse ***:");
    sb.writeln("----------------------------------------------------------------------------------------------------------------");
    sb.writeln("uri:       ${response.request.uri}");
    if (response.isRedirect) {
      sb.writeln("redirect:       ${response.realUri}");
    }
    sb.writeln("statusCode:       ${response.statusCode}");
    sb.writeln("----------------------------------------------------------------------------------------------------------------");
    sb.write(response.headers.toString());
    sb.writeln("----------------------------------------------------------------------------------------------------------------");
    sb.write(response.data.toString());
    logger.i(sb.toString());
    return super.onResponse(response);
  }
}
